// pages/edit-info/index.js
const app = getApp();
const api = app.api;
const wxutil = app.wxutil;

Page({
  data: {
    nickName: '',
    userId: -1,
    gender: 0,
    password: '',
    user_name: '',
  },

  onLoad() {
    this.getUserDetail();
  },

  /**
   * 获取用户详情
   */
  getUserDetail() {
    const userId = app.globalData.userDetail.id;
    const url = api.userAPI + userId + "/";

    wxutil.request.get(url).then((res) => {
      if (res.data.code == 200) {
        const user = res.data.data;
        this.setData({
          userId: user.id,
          nickName: user.nick_name,
          gender: user.gender,
          password: user.password,
          user_name: user.user_name,
        });
      }
    });
  },

  /**
   * 设置昵称
   */
  setNickName(event) {
    this.setData({
      nickName: event.detail.value,
    });
  },

  /**
   * 设置性别
   */
  onChangeGenderTap(event) {
    this.setData({
      gender: event.detail.key,
    });
  },

  setPassword(event) {
    this.setData({
      password: event.detail.value,
    });
  },

  /**
   * 保存用户信息
   */
  saveInfo() {
    // 获取表单数据
    const nickName = this.data.nickName;
    const gender = this.data.gender;
    const password = this.data.password;

    if (!wxutil.isNotNull(nickName)) {
      wx.lin.showMessage({
        type: "error",
        content: "昵称不能为空！",
      });
      return;
    }

    // 构造请求参数
    const url = api.userAPI;
    const data = [
      {
        op: "replace",
        path: "/nick_name",
        value: nickName,
      },
      {
        op: "replace",
        path: "/gender",
        value: gender,
      },
      {
        op: "replace",
        path: "/password",
        value: password,
      },
    ];

    // 更新用户信息
    wxutil.request.put(url, data).then((res) => {
      if (res.data.code == 200) {
        let userDetail = app.globalData.userDetail;
        // 更新缓存
        const user = res.data.data;
        userDetail = Object.assign(userDetail, user);
        wxutil.setStorage("userDetail", userDetail);
        app.globalData.userDetail = userDetail;

        wx.lin.showMessage({
          type: "success",
          content: "资料修改成功！",
          success() {
            wx.navigateBack();
          },
        });
      } else {
        wx.lin.showMessage({
          type: "error",
          content: "资料修改失败！",
        });
      }
    });
  },

  onShareAppMessage() {
    return {
      title: "编辑资料",
      path: "/pages/user-edit/index",
    };
  },
});
